import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_filereader/flutter_filereader.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_pdf_plugin/flutter_pdf_viewer.dart';
import 'package:path_provider/path_provider.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/12.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class PdfWidgetPage extends StatefulWidget {
  final String url;
  final String title;
  final bool isPdf;
  final bool showTitle;

  PdfWidgetPage(
      {@required this.url,
      this.title,
      this.isPdf = true,
      this.showTitle = false});

  @override
  _PdfWidgetPageState createState() => _PdfWidgetPageState();
}

class _PdfWidgetPageState extends State<PdfWidgetPage> {
  String _path;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    createFileOfPdfUrl().then((f) {
      setState(() {
        _path = f.path;
      });
    });
  }

  Future<File> createFileOfPdfUrl() async {
    final url = widget.url;
    String filename = url.substring(url.lastIndexOf("/") + 1);
    LogUtils.e(" filename $filename");
    // if (!widget.isPdf) {
    //   filename = filename + ".docx";
    // }
    LogUtils.e(" filename $filename");
    var request = await HttpClient().getUrl(Uri.parse(url));

    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    Directory externalStorageDirectory =
        await getApplicationDocumentsDirectory();
    String dir = externalStorageDirectory.path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    return file;
  }

  @override
  Widget build(BuildContext context) {
    if (_path == null) {
      return Scaffold(
        appBar: AppBar(
          title: Text("${widget.title}"),
        ),
        body: LoadingWidget(),
      );
    }

    LogUtils.e("预览 $_path");
    if (!widget.isPdf) {
      if (widget.showTitle) {
        return Scaffold(
          appBar: AppBar(
            title: Text("${widget.title}"),
          ),
          body: FileReaderView(
            filePath: _path,
          ),
        );
      }
      return FileReaderView(
        filePath: _path,
      );
    }
    return PdfScaffold(
      appBar: AppBar(
        title: Text("${widget.title}"),
      ),
      path: _path,
    );
  }
}
